const express = require('express');
const fs = require('fs');
const path = require('path');
const router = express.Router();

// 数据文件路径
const dataPath = path.join(__dirname, '../data/partners.json');

// 读取数据的辅助函数
const readData = () => {
  try {
    const data = fs.readFileSync(dataPath, 'utf8');
    return JSON.parse(data);
  } catch (error) {
    console.error('读取数据文件失败:', error);
    return { partners: [] };
  }
};

// 写入数据的辅助函数
const writeData = (data) => {
  try {
    fs.writeFileSync(dataPath, JSON.stringify(data, null, 2));
    return true;
  } catch (error) {
    console.error('写入数据文件失败:', error);
    return false;
  }
};

// 获取所有合作伙伴
router.get('/', (req, res) => {
  try {
    const data = readData();
    const { category, status, limit } = req.query;
    
    let partners = data.partners || [];
    
    // 按分类筛选
    if (category && category !== 'all') {
      partners = partners.filter(partner => partner.category === category);
    }
    
    // 按状态筛选
    if (status) {
      partners = partners.filter(partner => partner.status === status);
    }
    
    // 按排序字段排序
    partners.sort((a, b) => a.sortOrder - b.sortOrder);
    
    // 限制返回数量
    if (limit) {
      partners = partners.slice(0, parseInt(limit));
    }
    
    res.json({
      success: true,
      data: partners,
      total: partners.length,
      message: '获取合作伙伴列表成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error.message
    });
  }
});

// 获取单个合作伙伴
router.get('/:id', (req, res) => {
  try {
    const data = readData();
    const partner = data.partners.find(p => p.id === parseInt(req.params.id));
    
    if (!partner) {
      return res.status(404).json({
        success: false,
        message: '合作伙伴不存在'
      });
    }
    
    res.json({
      success: true,
      data: partner,
      message: '获取合作伙伴详情成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error.message
    });
  }
});

// 添加新合作伙伴
router.post('/', (req, res) => {
  try {
    const data = readData();
    const { name, description, category = 'food', status = 'active' } = req.body;
    
    if (!name || !description) {
      return res.status(400).json({
        success: false,
        message: '品牌名称和描述不能为空'
      });
    }
    
    // 生成新ID
    const newId = Math.max(...data.partners.map(p => p.id), 0) + 1;
    
    const newPartner = {
      id: newId,
      name,
      description,
      category,
      status,
      sortOrder: data.partners.length + 1,
      createdAt: new Date().toISOString()
    };
    
    data.partners.push(newPartner);
    
    if (writeData(data)) {
      res.status(201).json({
        success: true,
        data: newPartner,
        message: '添加合作伙伴成功'
      });
    } else {
      res.status(500).json({
        success: false,
        message: '保存数据失败'
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error.message
    });
  }
});

// 更新合作伙伴
router.put('/:id', (req, res) => {
  try {
    const data = readData();
    const partnerId = parseInt(req.params.id);
    const partnerIndex = data.partners.findIndex(p => p.id === partnerId);
    
    if (partnerIndex === -1) {
      return res.status(404).json({
        success: false,
        message: '合作伙伴不存在'
      });
    }
    
    const { name, description, category, status, sortOrder } = req.body;
    
    // 更新字段
    if (name) data.partners[partnerIndex].name = name;
    if (description) data.partners[partnerIndex].description = description;
    if (category) data.partners[partnerIndex].category = category;
    if (status) data.partners[partnerIndex].status = status;
    if (sortOrder) data.partners[partnerIndex].sortOrder = sortOrder;
    
    data.partners[partnerIndex].updatedAt = new Date().toISOString();
    
    if (writeData(data)) {
      res.json({
        success: true,
        data: data.partners[partnerIndex],
        message: '更新合作伙伴成功'
      });
    } else {
      res.status(500).json({
        success: false,
        message: '保存数据失败'
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error.message
    });
  }
});

// 删除合作伙伴
router.delete('/:id', (req, res) => {
  try {
    const data = readData();
    const partnerId = parseInt(req.params.id);
    const partnerIndex = data.partners.findIndex(p => p.id === partnerId);
    
    if (partnerIndex === -1) {
      return res.status(404).json({
        success: false,
        message: '合作伙伴不存在'
      });
    }
    
    const deletedPartner = data.partners.splice(partnerIndex, 1)[0];
    
    if (writeData(data)) {
      res.json({
        success: true,
        data: deletedPartner,
        message: '删除合作伙伴成功'
      });
    } else {
      res.status(500).json({
        success: false,
        message: '保存数据失败'
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error.message
    });
  }
});

module.exports = router;
